package com.itany.netclass.filter;


import com.itany.netclass.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Author:sjy@itany.com
 * Date:21-10-20 上午10:26
 * Version:1.0-SNAPSHOT
 * Description:
 */
public class LoginFilter implements Filter {
    private FilterConfig config;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.config=filterConfig;
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;
        User user1= (User) request.getSession().getAttribute("loginUser");
        User user2= (User) request.getSession().getAttribute("FloginUser");
        String path=request.getServletPath();
        if(path.equals("/showLogin.do")
                ||path.equals("/code/show.do")
                ||path.equals("/user/login.do")
                || path.startsWith("/showFrontMain")||path.endsWith("css")||path.endsWith("js")||path.endsWith("g")){
//            System.out.println(path);
//            System.out.println("不需要登录放行了");
            chain.doFilter(servletRequest,servletResponse);//表示放行，无此代码servletRequest,servletResponse无法进入服务器
        }else if (user1!=null &&( path.startsWith("/show")
                ||path.startsWith("/user")
                || path.startsWith("/resource")
                || path.startsWith("/manage")
                || path.startsWith("/courseType")
                || path.startsWith("/course")
                || path.startsWith("/comment")
                || path.startsWith("/chapter")
                || path.endsWith(".mp4")
                || path.endsWith(".pdf"))){
//            System.out.println(path);
//            System.out.println("登录放行了");

            chain.doFilter(servletRequest,servletResponse);
        }else if(user2!=null){
            chain.doFilter(servletRequest,servletResponse);
        }else {
            System.out.println(path);
            System.out.println("未登录不放行");
            request.getSession().setAttribute("loginMrg","未登录，请先登录");
            response.sendRedirect(request.getContextPath()+"/showLogin.do");
        }


    }

    @Override
    public void destroy() {

    }
}
